package com.lakala.sh.zf.openplatform.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;

/**
 * 生成摘要
 * @author: peijian
 * @date: 2021/1/18 16:47
 */
public class MessageDigestUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(MessageDigestUtil.class);

    private static final String SHA256 = "SHA-256";

    public static String getSHA256Digest(String content) {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance(SHA256);
            messageDigest.update(content.getBytes("utf-8"));
            return bytesToHexString(messageDigest.digest());
        } catch (Exception e) {
            LOGGER.error("sha256  digest", e);
        }

        return null;

    }


    /**
     * 将字节数组转换成16进制字符串
     * @param bytes
     * @return
     */
    private static String bytesToHexString(byte[] bytes){
        StringBuffer sb = new StringBuffer(bytes.length);
        String temp = null;
        for (int i = 0;i< bytes.length;i++){
            temp = Integer.toHexString(0xFF & bytes[i]);
            if (temp.length() <2){
                sb.append(0);
            }
            sb.append(temp);
        }
        return sb.toString();
    }

}
